//
//  AppDelegate.m
//  Project
//
//  Created by 冯东辉 on 2018/9/11.
//  Copyright © 2018年 FengDongHui. All rights reserved.
//

#import "AppDelegate.h"
#import "IQKeyboardManager.h"

#import "BaseTabBarController.h"
#import "LoginVC.h"
#import "GuestureLoginVC.h"
#import "GuestureVC.h"

#import <WXApi.h>

// 控制台中文输出
#import "JRSwizzle.h"
#import "NSDictionary+Unicode.h"

@interface AppDelegate () <LoginSuccessDelegate, WXApiDelegate>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 控制台中文输出
    [NSDictionary jr_swizzleMethod:@selector(description) withMethod:@selector(my_description) error:nil];
    
    // 修改手势密码
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setGuestureLoginRoot) name:@"CHANGEGUESTUREPSSUCCESSED" object:nil];
    
    // 切换账号
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeUserHundle) name:@"QIEHUANZHANGHAO" object:nil];
    
    // 忘记手势密码
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(forgetGuseturePs) name:@"FORGETGEUSTUREPASSWORD" object:nil];
    
    // HUD设置
    [self registerHud];
    
    // 键盘设置
    [self registerCustomKeyboard];
    
    [WXApi registerApp:WXAppID];
    
    // 获取登录状态
    NSString *phoneNum = [[NSUserDefaults standardUserDefaults] objectForKey:USER_PHONE_NUM];
    // 获取手势密码
    NSString *resultPassWord = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@_%@", DBGuestureLockPaswdResult, phoneNum]];
    // 是否是切换账号登录状态
    NSString *status = [[NSUserDefaults standardUserDefaults] objectForKey:IS_CHANGE_USER];
    
    if (status && [status isEqualToString:@"1"]) {
        
        // 展示登录页面
        [self setLoginRoot];
    }else {
        
        if (phoneNum && [phoneNum length] > 0 && resultPassWord && [resultPassWord length] > 0) {
            [self setGuestureLoginRoot];
        }else {
            [self setLoginRoot];
        }
    }
    
    [self checkNewVersion];
    
    return YES;
}

#pragma mark - 版本检测
- (void)checkNewVersion {
    
    NSString *app_Version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];

    [[ProjectApi instance] appUpdateIpaCallBack:^(NetModel *object) {
        
        if (object.isSuccessed) {
            
            NSDictionary *dic = [[object.service firstObject] firstObject];
            
            NSString *v_version = [NSString stringWithFormat:@"%@", dic[@"v_version"]];
            
            if (![v_version isEqualToString:app_Version]) {
                
                NSString *v_remark = [NSString stringWithFormat:@"%@", dic[@"v_remak"]];
                NSString *v_path = [NSString stringWithFormat:@"%@", dic[@"v_path"]];
                
                [self showNoteAlertView:v_path content:v_remark];
            }
        }
    }];
}

- (void)showNoteAlertView:(NSString *)url content:(NSString *)content {
    
    // 初始化
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"检测到有新版本，是否更新？" message:content preferredStyle:UIAlertControllerStyleAlert];
    
    // 取消
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertController addAction:cancelAction];
    
    // 确定
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
        
        [self exit];
    }];
    
    [alertController addAction:confirmAction];
    
    // 弹出
    [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
    }];
}

- (void)exit {
    
    exit(0);
}

/**
 * 切换账号处理
 */
- (void)changeUserHundle {
    
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:IS_CHANGE_USER];
    // 权限城市
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_CITY_DATA];
    // 默认城市
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:USER_INFO_CITY];
    
    [self setLoginRoot];
}

/**
 * 忘记手势密码处理
 */
- (void)forgetGuseturePs {
    
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//
//    NSString *phoneNum = [userDefaults objectForKey:USER_PHONE_NUM];
//
//    NSString *key = [NSString stringWithFormat:@"%@_%@", DBGuestureLockPaswdResult, phoneNum];
//
//    [userDefaults removeObjectForKey:key];
//    [userDefaults synchronize];
    
    [self setLoginRoot];
}

/**
 * 设置TabBar控制器为rootVC
 */
- (void)setTabBarRoot {
    
    BaseTabBarController *mainTab = [[BaseTabBarController alloc]init];
    self.window.rootViewController = mainTab;
}

/**
 * 设置登录页为rootVC
 */
- (void)setLoginRoot {
    
    LoginVC *loginVc = [[LoginVC alloc] init];
    loginVc.delegate = self;
    self.window.rootViewController = loginVc;
}

/**
 * 设置手势密码登录为rootVC
 */
- (void)setGuestureLoginRoot {
    
    GuestureLoginVC *loginVc = [[GuestureLoginVC alloc] init];
    loginVc.delegate = self;
    self.window.rootViewController = loginVc;
}

/**
 * 设置设置手势密码为rootVC
 */
- (void)setGuestureRoot {
    
    GuestureVC *loginVc = [[GuestureVC alloc] init];
    loginVc.delegate = self;
    loginVc.isFirstSetGuesturePs = YES;
    self.window.rootViewController = loginVc;
}

/**
 * 登录成功回调
 */
- (void)LoginSuccessCallBack {
    
    // 获取登录状态
    NSString *phoneNum = [[NSUserDefaults standardUserDefaults] objectForKey:USER_PHONE_NUM];
    // 获取手势密码
    NSString *resultPassWord = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@_%@", DBGuestureLockPaswdResult, phoneNum]];
    
    if (resultPassWord && [resultPassWord length] > 0) {
        // 设置root
        [self setTabBarRoot];
    }else {
        // 设置手势密码
        [self setGuestureRoot];
    }
}

/**
 * HUD设置
 */
- (void)registerHud {
    
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
}

/**
 * 键盘设置
 */
- (void)registerCustomKeyboard {
    
    IQKeyboardManager *kbManager =  [IQKeyboardManager sharedManager];
    kbManager.enableAutoToolbar = NO;
    kbManager.shouldResignOnTouchOutside = YES;
    kbManager.enable = YES;
}

-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    return [WXApi handleOpenURL:url delegate:self];
}

-(void)onReq:(BaseReq *)req {
    
    
}
// 从微信分享过后点击返回应用的时候调用
- (void)onResp:(BaseResp *)resp {
    
    //把返回的类型转换成与发送时相对于的返回类型,这里为SendMessageToWXResp
    SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
    
    //使用UIAlertView 显示回调信息
    NSString *str = @"分享成功";
    
    if (sendResp.errCode != 0) {
        
        str = sendResp.errStr;
    }

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:str preferredStyle:UIAlertControllerStyleAlert];
    
    // 取消
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:cancelAction];
    
    // 确定
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertController addAction:confirmAction];
    
    // 弹出
    [self.window.rootViewController presentViewController:alertController animated:YES completion:^{
    }];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
